package bubuntux.jusbscan.tui;

import jcurses.widgets.BorderPanel;
import jcurses.widgets.GridLayoutManager;
import jcurses.widgets.Label;
import jcurses.widgets.List;
import jcurses.widgets.ProgressBar;

import org.apache.commons.lang.StringUtils;

import bubuntux.jusbscan.core.Configs;

public class Frame extends BorderPanel {

	private Label info = null;
	private ProgressBar pBar = null;
	private List resume = null;

	public Frame() {
		super();
		this.init();

		GridLayoutManager manager = new GridLayoutManager(20, 10);
		this.setLayoutManager(manager);

		manager.addWidget(this.info, 1, 0, 18, 1, ALIGNMENT_BOTTOM,
				ALIGNMENT_CENTER);
		manager.addWidget(this.pBar, 1, 1, 18, 1, ALIGNMENT_CENTER,
				ALIGNMENT_CENTER);
		manager.addWidget(this.resume, 1, 2, 18, 8, ALIGNMENT_CENTER,
				ALIGNMENT_CENTER);

	}

	public void addResume(String resumenLine) {
		if (resumenLine != null) {
			this.resume.add(cleanString(resumenLine, Configs.stringLength - 1));
			if (this.resume.getItemsCount() > Configs.listHeigth) {
				this.resume.remove(0);
			}
		}
	}

	public synchronized void repaint() {
		super.repaint();
	}

	public void setInfo(String message) {
		if (message != null) {
			this.info.setText(cleanString(message, Configs.stringLength));
		}
	}

	public void sumProgressBar() {
		this.pBar.addProgress();
	}

	public void totalFiles(int filesCount) {
		this.pBar.setTotalFiles(filesCount);
		this.pBar.reset();
	}

	private String cleanString(String str, int length) {
		if (str == null) {
			str = "";
		} else if (str.length() > length) {
			str = StringUtils.abbreviateMiddle(str, "...", length);
		}
		return str;
	}

	private void init() {
		this.info = new Label("USB ");
		this.pBar = new ProgressBar();
		this.pBar.setFocusable(false);
		this.resume = new List();
		this.resume.setFocusable(false);
	}

}
